package com.wy.powerbuilder.controller.ld;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Controller
public class LoginController {
    @RequestMapping("login")
    public String login(){
        return "login";
    }
    @RequestMapping("unauth")
    public String unauth(){
        return "unauth";
    }
    @RequestMapping("welcome")
    public String welcome(){
        return "welcome";
    }
    @RequestMapping("index")
    public String index(String name, String pwd,String vcode, Model model, HttpServletRequest request){
        /**
         * 使用Shiro编写认证操作
         */
        HttpSession session=request.getSession();
        String loginCpacha=session.getAttribute("loginCpacha").toString();
        System.out.println(loginCpacha);
        System.out.println(vcode);
        if(!loginCpacha.equalsIgnoreCase(vcode)){
            model.addAttribute("msg","验证码输入错误");
            return "forward:login";
        }
        //1.获取Subject
        Subject subject= SecurityUtils.getSubject();
        //2.封装用户数据
        UsernamePasswordToken token=new UsernamePasswordToken(name,pwd);
        //3.执行登录方法

        try {
            subject.login(token);
            session.setAttribute("name",name);
            return "index";
            //登录成功
        }catch (UnknownAccountException e){
            model.addAttribute("msg","用户名不存在或者被注销");
            return "forward:login";
            //登录失败：用户名不存在
        }catch (IncorrectCredentialsException e){
            model.addAttribute("msg","密码错误");
            return "forward:login";
            //登录失败：密码错误
        }
    }
}
